//
//  QZTabbarController.m
//  QZBaseDemo
//
//  Created by QF_iOS on 2018/11/27.
//  Copyright © 2018年 QF_iOS. All rights reserved.
//

#import "QZTabbarController.h"
#import "QZCustomerNavigation.h"
#import "HomeVC.h"
#import "QZMapVC.h"
#import "QZTabBar.h"
#import "OneVC.h"
#import "TwoVC.h"
#import "ThreeVC.h"
#import "FourVC.h"
#import "TableHeaderAnimationVC.h"
#import "ZYImageCacheManager.h"
#import "UIImageView+WebCache.h"
#import "SGWebView.h"
#import "UIImage+Extension.h"
#import "UploadAvatarVC.h"
#import "SLWebViewController.h"

@interface QZTabbarController ()<UITabBarControllerDelegate>

@property (nonatomic, strong) QZTabBar *qzTabbar;
@property (nonatomic, assign) NSUInteger selectItem;//选中的item
@property (nonatomic, strong) NSDictionary *dictionaryChildList; //保存tabbar数据
@property (nonatomic, strong) NSArray *arrayChildList; //保存tabbar数据
@property (nonatomic, strong) OneVC *oneVC;


@end

@implementation QZTabbarController

- (void)viewDidLoad {
    [super viewDidLoad];
    _arrayChildList = [NSArray array];
    _qzTabbar = [[QZTabBar alloc] init];
    //中间按钮方法
//    [_qzTabbar.centerBtn addTarget:self action:@selector(touchCenterBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    //选中时的颜色
    _qzTabbar.tintColor = tabbarSelectColor;
    //透明设置为NO，显示为白色，view的高度到tabbar顶部截止，YES的话到底部
    _qzTabbar.translucent = NO;
    //利用KVC，将自己的tabbar赋值给系统的tabbar
    [self setValue:_qzTabbar forKey:@"tabBar"];
    //默认选中第几个
    self.selectItem = 0;
    COM.selectBarItem = 0;
    self.delegate = self;
//    [self childListAction];
    [self addChildViewControllers];
    //分割线的颜色
    [self setTabbarTopLineColor];
 
    
}
- (void)childListAction {
    NSDictionary *dict = @{@"logoId":LOGOID};
    NSString *urlString = [NSString stringWithFormat:@"%@%@",uHostURL,getAppMenu];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:urlString parameters:dict success:^(id obj) {
        NSDictionary *dic = (NSDictionary *)obj;
        NSString *errorcodeString = dic[@"errorcode"];
        if ([dic[@"data"] isEqual:[NSNull null]]) {
            return;
        }
        DLog(@"%@",obj);
        if (![errorcodeString isEqualToString:@"9999"]) {
            return;
        }
        
        NSString *bgColor = dic[@"appMenu"][@"bgColor"];
       
        
       //保存tabbaritem
        self->_arrayChildList = dic[@"data"][@"childList"];
        [self addChildViewControllers];
       
    } fail:^(NSError *error) {
        
    }];
}


- (void)addChildViewControllers {
    
    NSArray *array = COM.childArray;
    if (array.count == 0) {
        NSLog(@"加载没有TabbarItem")
        QZCustomerNavigation *navigation = [[QZCustomerNavigation alloc] initWithRootViewController:[[OneVC alloc] init]];
        [self addChildViewController:navigation];
    } else {
        for (int i=0; i<array.count; i++) {
            NSLog(@"加载tabbarItem")
            NSString *titleStirng = [NSString stringWithFormat:@"%@", array[i][@"title"]];
            NSString *defaultIconURL = [NSString stringWithFormat:@"%@%@", uHostURL_IMAGE, array[i][@"defaultIcon"]];
            NSString *selectedIconURL = [NSString stringWithFormat:@"%@%@", uHostURL_IMAGE, array[i][@"selectedIcon"]];
            NSString *defaultIcon = [NSString stringWithFormat:@"%d.png",i];
            NSString *selectedIcon = [NSString stringWithFormat:@"%d.png",i];
            [self addImageChildVC:[[OneVC alloc] init] andTitle:titleStirng andImageName:defaultIcon selectImageName:selectedIcon defaultImage:defaultIconURL selectedIcon:selectedIconURL];
        }
    }
   
    
    //图片大小建议32 * 32
//    [self addChildVC:[[UploadAvatarVC alloc] init] andTitle:@"消息" andImageName:@"消息" selectImageName:@"消息选中"];
//    [self addChildVC:[[OneVC alloc] init] andTitle:@"wode" andImageName:@"消息" selectImageName:@"消息选中"];
//    [self addChildVC:[[TwoVC alloc] init] andTitle:@"通讯录" andImageName:@"通讯录" selectImageName:@"通讯录选中"];
////    [self addChildVC:[[HomeVC alloc] init] andTitle:@"中间" andImageName:@"" selectImageName:@""];//只是占位的效果
//    [self addChildVC:[[ThreeVC alloc] init] andTitle:@"工作台" andImageName:@"工作台" selectImageName:@"工作台选中"];
//    [self addChildVC:[[TableHeaderAnimationVC  alloc] init] andTitle:@"我的" andImageName:@"我的" selectImageName:@"我的选中"];
    
    
}


- (void)addImageChildVC:(UIViewController *)childVC andTitle:(NSString *)title andImageName:(NSString *)name selectImageName:(NSString *)selectImageName defaultImage:(NSString *)defaultImage selectedIcon:(NSString *)selectedIcon {
    
    NSLog(@"defaultImage: %@ \n selectedIcon：%@",defaultImage,selectedIcon);
    
    childVC.tabBarItem.image = [UIImage imageNamed:name];
    childVC.tabBarItem.selectedImage = [[UIImage imageNamed:selectImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVC.title = title;
    
//    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:defaultImage] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//           if (!error && finished) {
////               CGFloat size = cgsi
//               [UIImage imageWithOriginImage:image scaleToSize:CGSizeMake(32, 32)];
//               childVC.tabBarItem.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//           }
//      }];
//
//      [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:selectImageName] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//           if (!error && finished) {
//               childVC.tabBarItem.selectedImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//           }
//      }];

//
    
    //调整图片和文字的位置
//    UIEdgeInsets ImageInsets = UIEdgeInsetsMake(3, 0, -3, 0 );
//    childVC.tabBarItem.imageInsets = ImageInsets;
    QZCustomerNavigation *navigation = [[QZCustomerNavigation alloc] initWithRootViewController:childVC];
    [self addChildViewController:navigation];
    
}

- (void)addChildVC:(UIViewController *)childVC andTitle:(NSString *)title andImageName:(NSString *)name selectImageName:(NSString *)selectImageName {

    childVC.tabBarItem.image = [UIImage imageNamed:name];
    childVC.tabBarItem.selectedImage = [[UIImage imageNamed:selectImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVC.title = title;
    //调整图片和文字的位置
//    UIEdgeInsets ImageInsets = UIEdgeInsetsMake(3, 0, -3, 0 );
//
//    childVC.tabBarItem.imageInsets = ImageInsets;
    
    QZCustomerNavigation *navigation = [[QZCustomerNavigation alloc] initWithRootViewController:childVC];
    [self addChildViewController:navigation];

}
//中间按钮的点击
- (void)touchCenterBtnAction:(UIButton *)sender {
    self.selectedIndex = 2;//关联中间按钮
    if (self.selectItem != 2) {
        [self rotationAnimation];
    }
    self.selectItem = 2;
}

//tabbar选择时候代理
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    if (tabBarController.selectedIndex == 2) {//选中中间的按钮
        if (self.selectItem != 2) {
            [self rotationAnimation];
            
        }
        
    } else {
        [_qzTabbar.centerBtn.layer removeAllAnimations];
    }
    self.selectItem = tabBarController.selectedIndex;
    COM.selectBarItem = self.selectItem;
    NSLog(@"tabBarController.selectedIndex:%lu",(unsigned long)self.selectItem);
}

//旋转动画
- (void)rotationAnimation{
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI*2.0];
    rotationAnimation.duration =1;
    rotationAnimation.repeatCount = 1;
    [_qzTabbar.centerBtn.layer addAnimation:rotationAnimation forKey:@"key"];
}

#pragma mark -- 设置tabbar顶部的线
- (void)setTabbarTopLineColor {
    //该表tabbard线条的颜色
    CGRect rect = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, RGB(255, 255, 255, 1).CGColor);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //两个方法缺一不可，否则将无法改变分割线颜色
    [_qzTabbar setShadowImage:img];
    [_qzTabbar setBackgroundImage:[[UIImage alloc] init]];
    
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


//NSArray *titles = @[L(@"首页"), L(@"新闻"), L(@"消息"), L(@"我的")];
//
//NSArray *images = @[@"bottom_tabbar_home", @"bottom_tabbar_news", @"bottom_tabbar_message", @"bottom_tabbar_my"];
//
//NSArray *imagesSel = @[@"bottom_tabbar_home_selected", @"bottom_tabbar_news_selected", @"bottom_tabbar_message_selected", @"bottom_tabbar_my_selected"];
//
//NSMutableArray * tabarr = [NSMutableArray new];
//
//[tabarr addObject:[self createChildrenCtrWithtitle:titles[0]]];
//
//[tabarr addObject:[self createChildrenCtrWithtitle:titles[1]]];
//
//[tabarr addObject:[self createChildrenCtrWithtitle:titles[2]]];
//
//[tabarr addObject:[self createChildrenCtrWithtitle:titles[3]]];
//
//self.viewControllers = tabarr;
//
//[self.tabBar.items enumerateObjectsUsingBlock:^(UITabBarItem *item, NSUInteger idx, BOOL *stop) {
//    item.title = titles[idx];
//    UIImage *img = [UIImage imageNamed:images[idx]];
//    UIImage *selectImg = [UIImage imageNamed:imagesSel[idx]];
//    item.image =  [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    item.selectedImage = [selectImg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//}];

@end
